import service from "@service";
import { flatNodesToNodes,getDataMapFromNodes, treeFilter } from "@utils";

export default {
    namespaced: true,
    state: {
        dictMap: {},
        dictMapMap: {},
        loadingDictMap: {},
        dictAsyncMap: {},

        dictMapBu:{},
        loadingDictMapBu: {},
        dictAsyncMapBu: {},
        dictMapMapBu: {},
    },
    mutations: {
        SET_DICT(state, payload) {
            state.dictMap[payload.key] = payload.data;
            if (payload.dataMap) {
                state.dictMapMap[payload.key] = payload.dataMap;
            }
        },
        ADD_DICT_LOADING(state, payload) {
            if (state.loadingDictMap[payload.key]) {
                state.loadingDictMap[payload.key] = [payload];
            } else {
                state.loadingDictMap[payload.key].push(payload);
            }
        },
        CLEAR_DICT_LOADING(state, payload) {
            state.loadingDictMap[payload.key] = null;
        },
        SET_ASYNC_DICT(state, payload) {
            state.dictAsyncMap[payload.key] = payload.data;
        },


        SET_DICTBU(state, payload) {
            state.dictMapBu[payload.key] = payload.data;
            if (payload.dataMap) {
                state.dictMapMapBu[payload.key] = payload.dataMap;
            }
        },
        ADD_DICT_LOADINGBU(state, payload) {
            if (state.loadingDictMapBu[payload.key]) {
                state.loadingDictMapBu[payload.key] = [payload];
            } else {
                state.loadingDictMapBu[payload.key].push(payload);
            }
        },
        CLEAR_DICT_LOADINGBU(state, payload) {
            state.loadingDictMapBu[payload.key] = null;
        },
        SET_ASYNC_DICTBU(state, payload) {
            state.dictAsyncMapBu[payload.key] = payload.data;
        },
    },
    actions: {
        async getCfgTree({ state, commit }, params) {
            const { dictMap, dictMapMap } = state;

            let key = null;

            if (!params) {
                return;
            }
            let tempParams = {};

            if (typeof params === "string") {
                key = params;
                tempParams = { key: params }
            } else {
                tempParams = params;
                key = params.service;
            }

            // nodesFilterHandle： 节点筛选函数
            // filterNodesKey: 缓存筛选后的节点集合的key名
            // cache: 当前数据是否从缓存取
            // dataIsFlat：当前数据是否是平铺的数据，false表示一个节点树形结构
            let { nodesFilterHandle, filterNodesKey, cache = true, dataIsFlat=true } = tempParams;

            let isFilter = nodesFilterHandle && filterNodesKey;

            if (cache) {

                if (dictMap[key] && !isFilter) {
                    return {
                        data: dictMap[key],
                        dataMap: dictMapMap[key]
                    };
                } else if (dictMap[filterNodesKey] && isFilter) {
                    return {
                        data: dictMap[filterNodesKey],
                        dataMap: dictMapMap[filterNodesKey]
                    };
                }
            }

            if (state.loadingDictMap[key]) {
                return new Promise(resolve => {
                    commit("ADD_DICT_LOADING", data => {
                        resolve(data);
                    });
                });
            }

            const serviceParams = {
                noMessageTip: true
            }
            if (params.params) {
                serviceParams.params = params.params
            } else if (params.data) {
                serviceParams.data = params.data
            }

            let data = await service(key, serviceParams) || [];

            if(typeof params.dataFormatHandle === "function"){
                data = params.dataFormatHandle(data);
            }

            let dataMap = {};
            let nodes = [];

            if(dataIsFlat) {
                data.forEach(item => {
                    dataMap[item.id] = item;
                })
                nodes = flatNodesToNodes(data);
            }else {
                nodes= data;
                dataMap = getDataMapFromNodes(nodes);
            }
                

            let filterNodes = [];

            if (isFilter) {
                filterNodes = nodesFilterHandle(nodes);
                commit("SET_DICT", {
                    key: filterNodesKey,
                    data: filterNodes,
                });
            }

            commit("SET_DICT", {
                key,
                data: nodes,
                dataMap
            });


            if (state.loadingDictMap[key]) {
                state.loadingDictMap[key].forEach(f => {
                    f({ data: isFilter ? filterNodes : nodes, dataMap });
                });

                commit("CLEAR_DICT_LOADING");
            }

            return { data: isFilter ? filterNodes : nodes, dataMap };
        },

        async getCfgTreeBu({ state, commit }, params) {
            const { dictMapBu, dictMapMapBu } = state;

            let key = null;

            if (!params) {
                return;
            }
            let tempParams = {};

            if (typeof params === "string") {
                key = params;
                tempParams = { key: params }
            } else {
                tempParams = params;
                key = params.service;
            }

            // nodesFilterHandle： 节点筛选函数
            // filterNodesKey: 缓存筛选后的节点集合的key名
            // cache: 当前数据是否从缓存取
            // dataIsFlat：当前数据是否是平铺的数据，false表示一个节点树形结构
            let { nodesFilterHandle, filterNodesKey, cache = true, dataIsFlat=true } = tempParams;

            let isFilter = nodesFilterHandle && filterNodesKey;

            if (cache) {

                if (dictMapBu[key] && !isFilter) {
                    return {
                        data: dictMapBu[key],
                        dataMap: dictMapMapBu[key]
                    };
                } else if (dictMapBu[filterNodesKey] && isFilter) {
                    return {
                        data: dictMapBu[filterNodesKey],
                        dataMap: dictMapMapBu[filterNodesKey]
                    };
                }
            }

            if (state.loadingDictMapBu[key]) {
                return new Promise(resolve => {
                    commit("ADD_DICT_LOADINGBU", data => {
                        resolve(data);
                    });
                });
            }

            const serviceParams = {
                noMessageTip: true
            }
            if (params.params) {
                serviceParams.params = params.params
            } else if (params.data) {
                serviceParams.data = params.data
            }

            let data = await service(key, serviceParams) || [];

            if(typeof params.dataFormatHandle === "function"){
                data = params.dataFormatHandle(data);
            }

            let dataMap = {};
            let nodes = [];

            if(dataIsFlat) {
                data.forEach(item => {
                    dataMap[item.id] = item;
                })
                nodes = flatNodesToNodes(data);
            }else {
                nodes= data;
                dataMap = getDataMapFromNodes(nodes);
            }
                

            let filterNodes = [];

            if (isFilter) {
                filterNodes = nodesFilterHandle(nodes);
                commit("SET_DICTBU", {
                    key: filterNodesKey,
                    data: filterNodes,
                });
            }

            commit("SET_DICTBU", {
                key,
                data: nodes,
                dataMap
            });


            if (state.loadingDictMapBu[key]) {
                state.loadingDictMapBu[key].forEach(f => {
                    f({ data: isFilter ? filterNodes : nodes, dataMap });
                });

                commit("CLEAR_DICT_LOADINGBU");
            }

            return { data: isFilter ? filterNodes : nodes, dataMap };
        },
        // 异步树
        // async getCfgAsyncTree({ state, commit }, params){
        //     const { dictAsyncMap } = state;
        //     let {codeTypeCd,parentCode} = params;
        //     if(dictAsyncMap[codeTypeCd] && parentCode === '0'){//根
        //         return dictAsyncMap[codeTypeCd];
        //     }
        //     let result = await queryCallCfgAsynTree({
        //         codeTypeCd,parentCode
        //     });
        //     let data = renameTreeField(result, {
        //         nameMap: {
        //             bizCode: "value",
        //             codeFullName: "label",
        //             leafYn: "leaf"
        //         }
        //     });
        //     if(!(Object.keys(dictAsyncMap).includes(codeTypeCd)) && parentCode === '0'){//根
        //         commit("SET_ASYNC_DICT", {
        //             key:codeTypeCd,
        //             data
        //         });
        //     }
        //     return data;
        // }
    },
    getters: {}
};
